﻿using System;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using System.Configuration;
using System.Collections.Generic;
using System.Net;
using System.Data;
using System.Reflection;
using System.Diagnostics;

namespace Warehouse
{
    public partial class ReportForm : Form
    {
        ReportForm()
        {
            InitializeComponent();
            this.Load += delegate { viewer.RefreshReport(); };
        }

        public static ReportForm Create(string reportName, IEnumerable<Tuple<string, string>> parameters)
        {
            var form = new ReportForm();
            var viewer = form.viewer;
            viewer.ProcessingMode = ProcessingMode.Remote;
            viewer.ShowParameterPrompts = false;
            viewer.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServerUrl"], UriKind.Absolute);
            viewer.ServerReport.ReportPath = "/WarehouseReports/" + reportName;
            viewer.ServerReport.ReportServerCredentials.NetworkCredentials = 
                new NetworkCredential
                {
                    Domain = Dns.GetHostEntry(viewer.ServerReport.ReportServerUrl.Host).HostName,
                    UserName = ConfigurationManager.AppSettings["ReportsUser"],
                    Password = ConfigurationManager.AppSettings["ReportsUserPassword"],
                }; 
            foreach (var p in parameters)
            {
                viewer.ServerReport.SetParameters(new ReportParameter(name: p.Item1, value: p.Item2));
            }

            return form;
        }

        public static ReportForm CreateLocal(string reportName, DataTable dataSource, string sourceName = "local")
        {
            var form = new ReportForm();
            var report = form.viewer.LocalReport;
            report.ReportEmbeddedResource = reportName;
            report.DataSources.Add(new ReportDataSource(sourceName, dataSource));
            return form;
        }

        public static void ShowReportDialog(string reportName, IEnumerable<Tuple<string, string>> parameters)
        {
            Create(reportName, parameters).ShowDialog();
        }

        public static void ShowLocalReportDialog(string reportName, DataTable dataSource, string sourceName = "local")
        {
            CreateLocal(reportName, dataSource, sourceName).ShowDialog();
        }

        public byte[] GetPDF()
        {
            return this.viewer.ServerReport.Render("PDF");
        }
    }
}
